const board = document.getElementById('board');
const resetButton = document.getElementById('reset');
const undoButton = document.getElementById('undo');
let currentPlayer = 'x';
const gameState = Array(15).fill(null).map(() => Array(15).fill(null));
let moveHistory = [];

function createBoard() {
    for (let row = 0; row < 15; row++) {
        for (let col = 0; col < 15; col++) {
            const cell = document.createElement('div');
            cell.classList.add('cell');
            cell.dataset.row = row;
            cell.dataset.col = col;
            cell.addEventListener('click', handleCellClick);
            board.appendChild(cell);
        }
    }
}

function handleCellClick(event) {
    const row = parseInt(event.target.dataset.row);
    const col = parseInt(event.target.dataset.col);

    if (gameState[row][col] || checkWinner()) return;

    // 临时落子检查
    gameState[row][col] = currentPlayer;

    // 检查禁手
    if (currentPlayer === 'x' && checkForbidden(row, col)) {
        gameState[row][col] = null;
        return;
    }

    // 正式落子
    moveHistory.push({ player: currentPlayer, row, col });
    event.target.classList.add(currentPlayer);

    if (checkWinner()) {
        setTimeout(() => alert(`${currentPlayer === 'x' ? '红方' : '蓝方'} 胜利!`), 100);
    } else {
        currentPlayer = currentPlayer === 'x' ? 'o' : 'x';
    }
}

function checkWinner() {
    for (let row = 0; row < 15; row++) {
        for (let col = 0; col < 15; col++) {
            if (gameState[row][col] && checkDirection(row, col)) {
                return true;
            }
        }
    }
    return false;
}

function checkDirection(row, col) {
    const directions = [
        { dr: 1, dc: 0 },  // 垂直
        { dr: 0, dc: 1 },  // 水平
        { dr: 1, dc: 1 },  // 斜向右下
        { dr: 1, dc: -1 }  // 斜向左下
    ];

    for (const { dr, dc } of directions) {
        let count = 1;

        for (let step = 1; step < 5; step++) {
            const newRow = row + dr * step;
            const newCol = col + dc * step;
            if (newRow < 0 || newRow >= 15 || newCol < 0 || newCol >= 15 || gameState[newRow][newCol] !== gameState[row][col]) {
                break;
            }
            count++;
        }

        for (let step = 1; step < 5; step++) {
            const newRow = row - dr * step;
            const newCol = col - dc * step;
            if (newRow < 0 || newRow >= 15 || newCol < 0 || newCol >= 15 || gameState[newRow][newCol] !== gameState[row][col]) {
                break;
            }
            count++;
        }

        if (count >= 5) {
            return true;
        }
    }
    return false;
}

function checkForbidden(row, col) {
    if (currentPlayer !== 'x') return false; // 仅黑方受限制

    // 长连禁手
    if (checkOverline(row, col)) {
        alert("长连禁手！");
        return true;
    }

    // 三三禁手
    if (checkDoubleThree(row, col)) {
        alert("三三禁手！");
        return true;
    }

    return false;
}

function checkOverline(row, col) {
    const directions = [[1, 0], [0, 1], [1, 1], [1, -1]];
    for (const [dr, dc] of directions) {
        let count = 1;
        for (let i = 1; i < 6; i++) {
            const nr = row + dr * i, nc = col + dc * i;
            if (nr >= 15 || nc >= 15 || gameState[nr]?.[nc] !== currentPlayer) break;
            count++;
        }
        for (let i = 1; i < 6; i++) {
            const nr = row - dr * i, nc = col - dc * i;
            if (nr < 0 || nc < 0 || gameState[nr]?.[nc] !== currentPlayer) break;
            count++;
        }
        if (count > 5) return true;
    }
    return false;
}

function checkDoubleThree(row, col) {
    let threeCount = 0;
    const directions = [[1, 0], [0, 1], [1, 1], [1, -1]];

    for (const [dr, dc] of directions) {
        if (isOpenThree(row, col, dr, dc)) {
            threeCount++;
            if (threeCount >= 2) return true;
        }
    }
    return false;
}

function isOpenThree(row, col, dr, dc) {
    let count = 1;
    let openEnds = 0;

    // 正向检查
    for (let i = 1; i <= 3; i++) {
        const nr = row + dr * i;
        const nc = col + dc * i;
        if (nr >= 15 || nc >= 15) break;
        if (gameState[nr][nc] !== currentPlayer) {
            if (gameState[nr][nc] === null) openEnds++;
            break;
        }
        count++;
    }

    // 反向检查
    for (let i = 1; i <= 3; i++) {
        const nr = row - dr * i;
        const nc = col - dc * i;
        if (nr < 0 || nc < 0) break;
        if (gameState[nr][nc] !== currentPlayer) {
            if (gameState[nr][nc] === null) openEnds++;
            break;
        }
        count++;
    }

    return count === 3 && openEnds >= 2;
}

resetButton.addEventListener('click', () => {
    gameState.forEach(row => row.fill(null));
    document.querySelectorAll('.cell').forEach(cell => {
        cell.classList.remove('x', 'o');
    });
    currentPlayer = 'x';
    moveHistory = [];
});

undoButton.addEventListener('click', () => {
    if (moveHistory.length === 0) return;

    const lastMove = moveHistory.pop();
    gameState[lastMove.row][lastMove.col] = null;
    const cell = document.querySelector(`.cell[data-row="${lastMove.row}"][data-col="${lastMove.col}"]`);
    cell.classList.remove('x', 'o');
    currentPlayer = lastMove.player; // 恢复上一个玩家
});

createBoard();